<template>
  <a-modal
    :width="modalWidth"
    :title="form.title"
    :visible="form.visible"
    :confirm-loading="form.loading"
    :maskClosable="false"
    @ok="onSubmit"
    @cancel="onClose"
  >
    <a-form-model
      ref="DatasourcePermissionForm"
      :model="form.data"
      :rules="formRules"
      :label-col="{ span: 2 }"
      :wrapper-col="{ span: 22 }"
    >

      <a-form-model-item label="数据源ID" prop="datasourceId">
        <a-select
          v-model="form.data.datasourceId"
          show-search
          placeholder="请选择数据源"
          style="width: 200px"
          :default-active-first-option="false"
          :show-arrow="true"
          :filter-option="false"
          :not-found-content="null"
          :option-label-prop="'label'"
          @change="changeDatasource"
          :disabled="form.type === 'edit'"
        >
          <a-select-option v-for="item in datasourceList" :key="item.id" :label="item.name">
            {{ item.name }}
          </a-select-option>
        </a-select>
      </a-form-model-item>
      <a-form-model-item style="margin-top:10px;" label="筛选条件" prop="config" v-if="type === 0">
        <a-button v-on:click="addRule" :disabled="!eventProperties || eventProperties.length < 1">添加筛选</a-button>
        <MultiLevelFilter
          ref="filter"
          v-model="form.data.config"
          v-bind:datasource-id="form.data.datasourceId"
          v-bind:properties="eventProperties"
          v-on:remove="demote"
        >
        </MultiLevelFilter>
      </a-form-model-item>
      <a-form-model-item label="说明" prop="remark">
        <a-input v-model="form.data.remark" type="textarea" style="width: 300px" placeholder="请输入项目权限说明..." />
      </a-form-model-item>
    </a-form-model>
  </a-modal>
</template>

<script>
import MultiLevelFilter from "@/views/components/Filter/MultiLevelFilter";
import {mapActions} from "vuex";

export default {
  name: "datasourcePermissionConfig",
  components: { MultiLevelFilter },
  props: {
    form: Object,
    datasourceList: Array,
  },
  data () {
    return {
      modalWidth: 1200,
      eventProperties: [],
      userProperties: [],
      type: 0,
      formRules: {
        datasourceId: [
          {
            required: true,
            trigger: 'blur',
            message: '请选择项目'
          }
        ],
        config: [
          {
            required: true,
          }
        ],
        remark: [
          {
            max: 255,
            trigger: 'blur',
            message: '备注不能超出255个字符'
          }
        ]
      }
    }
  },
  computed: {},
  watch: {
    "form.visible" (){
      if (this.form.visible){
        this.type = this.form.data.type !== null ? this.form.data.type:0
        if (this.form.data.datasourceId){
          this.changeDatasource(this.form.data.datasourceId)
        }
      }else {
        this.$refs.DatasourcePermissionForm.clearValidate()
      }
    }
  },
  methods:{
    ...mapActions('orgManage', ['addOrgPermission','updateOrgPermission']),
    ...mapActions('analyseType', ['getPropertiesEvent']),
    addRule() {
      this.$refs.filter.addRule();
    },
    demote: function (index) {
      let filterIndex = this.form.data.config.filters.findIndex((item) => {
        return item.index === index;
      });
      if(filterIndex !== -1) {
        let filter = this.form.data.config.filters[filterIndex];
        this.form.data.config.filters.splice(filterIndex, 1);
        this.form.data.config.condition = filter.condition;
        filter.rules.forEach((item, index) => {
          this.form.data.config.rules.push(item);
        });
        filter.filters.forEach((item, index) => {
          this.form.data.config.filters.push(item);
        });
      }
    },
    checkQueryConfig_deep(obj){
      if(!obj){
        return true;
      }
      if(obj.condition&&obj.rules&&obj.rules.length==0){
        return true
      }
      let deep_bool = true;

      if(obj.rules&&obj.rules.length>0){
        obj.rules.map((_i,_in)=>{
          deep_bool = this.checkQueryConfig_deep(_i);
        })
      }
      if(obj.property === ''  || obj.operator === '') {
        deep_bool = false;
      } else if(obj.operator&&obj.operator.indexOf("is") !== 0 &&
        ((obj.value === '' || obj.value === null)
          && obj.values.length === 0)) {
        deep_bool = false;
      }
      return deep_bool;
    },
    validateConfig (rule, value, callback) {
      let filter_bool = this.checkQueryConfig_deep(this.form.data.config);
      if(!filter_bool){
        callback(new Error('筛选条件配置不正确'));
      }else {
        callback();
      }
    },
    onSubmit(){
      this.$refs.DatasourcePermissionForm.validate(valid => {
        if (valid) {
          this.form.loading = true
          if (!this.checkQueryConfig_deep(this.form.data.config)){
            this.$message.error('筛选条件配置异常')
            this.form.loading = false
            return
          }
          if (this.form.type === 'edit') {
            const data = JSON.parse(JSON.stringify(this.form.data))
            data.orgId = this.form.orgId
            data.config = JSON.stringify(data.config)
            this.updateOrgPermission(data)
              .then(() =>  {
                this.form.visible = false
                this.$message.success('项目权限修改成功')
              })
              .catch(err => this.$message.error('修改项目权限失败，原因：' + err.msg + '！'))
              .finally(() => {
                this.$emit('refreshPermissionList')
                this.form.loading = false
              })
          }else {
            const data = JSON.parse(JSON.stringify(this.form.data))
            data.orgId = this.form.orgId
            data.config = JSON.stringify(data.config)
            this.addOrgPermission(data)
              .then(() =>  {
                this.form.loading = false
                this.form.visible = false
                this.$message.success('项目权限添加成功')
              }).catch(err => this.$message.error('项目权限添加失败，原因：' + err.msg + '！'))
              .finally(() => {
                this.form.loading = false
                this.$emit('refreshPermissionList')
              })
          }
        } else {
          setTimeout(()=>{
            this.form.loading = false
            return false
          }, 200)
        }
      })
    },
    onClose(){
      this.form.visible = false
    },
    changeDatasource (datasourceId) {
      if (datasourceId == null){
        return
      }
      let type = 0
      for (let i in this.datasourceList){
        if (this.datasourceList[i].id === datasourceId){
          type = this.datasourceList[i].type
          break
        }
      }
      this.type = type
      if (type === 0 ){
        this.getProperties(datasourceId)
      }
    },
    getProperties (datasourceId) {
      if (datasourceId == null){
        return
      }
      this.getPropertiesEvent(datasourceId).then(res=>{
        console.log(datasourceId)
        this.eventProperties = [...res.data]
      })
    }
  }
}
</script>

<style scoped>

</style>
